<template>
  <section class="todoapp">
    <!-- 除了驼峰, 还可以使用-转换链接 -->
    <!-- 吧list传给子,自定义属性allDone全选操作,pushTodo操作push到数组 -->
    <TodoHeader
      :list="list"
      @allDone="allDoneFn"
      @pushTodo="pushTodoFn"
    />
    <!-- 吧seacherList传给子，isDone自定义属性调用选中，delTod自定义属性调用删除 -->
    <TodoMain
      :list="seacherList"
      @isDone="isDoneFn"
      @delTod="delTodFn"
    />
    <!-- 吧list传给子，吧type传给子，clickType切换高亮，clearDone 删除完成的 -->
    <TodoFooter
      :list="list"
      :type="type"
      @clickType="clickTypeFn"
      @clearDone="clearDoneFn"
    />
  </section>
</template>

<script>
// 1.0 样式引入
import "./styles/base.css"
import "./styles/index.css"
    
import TodoHeader from "./components/TodoHeader";
import TodoMain from "./components/TodoMain";
import TodoFooter from "./components/TodoFooter";


export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      // list: [
      //   { id: 100, name: "吃饭", isDone: true },
      //   { id: 101, name: "睡觉", isDone: false },
      //   { id: 102, name: "打豆豆", isDone: true },
      // ],
      list: JSON.parse(localStorage.getItem('todolist')),
      // type来区分高亮显示
      type: 'all'
    };
  },
  methods: {
    // 选中方法
    isDoneFn(id){
      // console.log(id)
      // 遍历找到相同ID的单元然后取反
      this.list.forEach(item => {
        if(item.id === id){
          item.isDone = !item.isDone
        }
      })
    },
    // 删除的方法
    delTodFn(id){
      // 遍历不包含相同ID的单元赋值给原数组
      this.list = this.list.filter(item => item.id != id)
    },
    // 全选的方法
    allDoneFn(val){
      // console.log(val);
      // 遍历修改每一项
      this.list.forEach(item => item.isDone = val)
    },
    // 添加方法
    pushTodoFn(val){
      // push一个对象
      this.list.push({
        // ID为最后一项ID-1
        id: this.list.at(-1).id + 1,
        name: val,
        isDone: false
      })
    },
    // 修改type
    clickTypeFn(val){
      this.type = val
    },
    // 删除完成的
    clearDoneFn(){
      this.list = this.list.filter(item => !item.isDone)
    }
  },
  computed:{
    // 删选数组
    seacherList(){
      if(this.type === 'yes'){
        return this.list.filter(item => item.isDone)
      } else if(this.type === 'no'){
        return this.list.filter(item => !item.isDone)
      } else {
        return this.list
      }
    },
  },
  watch:{
    list:{
      deep: true,
      handler(){
        localStorage.setItem('todolist', JSON.stringify(this.list))
      }
    }
  }
};
</script>